package com.naja.auth2server.security;

import com.naja.auth2server.entity.User;
import com.naja.auth2server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Arrays;
import java.util.List;

/**
 */
@Slf4j
public class LoginUserService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<User> users = this.userService.lambdaQuery().eq(User::getUserName, username).or().eq(User::getEmail, username).or().eq(User::getMobile, username).list();
        if (users.isEmpty()) {
            log.warn("用户[{}]不存在", username);
            throw new UsernameNotFoundException(String.format("用户[%s]不存在", username));
        }
        User user = users.get(0);
        return new LoginUser(username,user.getPassword(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")),user);
    }

}

